# -*- coding: utf-8 -*-
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse, Http404
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView, UpdateView
from django.views.generic.list import ListView
from main.models import Unit
from trainings.models import TrainingsRSIS, TrainingsWORK
from datetime import datetime

def get_args_model(obj):
    if obj.kwargs.get('arg', None) == 'rsis':
        return TrainingsRSIS._meta.module_name
    elif obj.kwargs.get('arg', None) == 'workers':
        return TrainingsWORK._meta.module_name
    else:
        raise Http404()


def get_args_model_class(obj):
    if obj.kwargs.get('arg', None) == 'rsis':
        return TrainingsRSIS
    elif obj.kwargs.get('arg', None) == 'workers':
        return TrainingsWORK
    else:
        raise Http404()


class TrainingsList(ListView):
    template_name = 'trainings/trainings_list.html'

    def get_queryset(self):
        return get_args_model_class(self).objects.all().order_by('-date')

    def get_context_data(self, **kwargs):
        if not self.request.user.has_perm("trainings.can_view_%s" % get_args_model(self)):
            raise PermissionDenied
        context = super(TrainingsList, self).get_context_data(**kwargs)
        context['argument'] = self.kwargs.get('arg')
        return context


class TrainingsDetail(DetailView):
    template_name = 'trainings/trainings_detail.html'

    def get_queryset(self):
        return get_args_model_class(self).objects.all()

    def get_context_data(self, **kwargs):
        if not self.request.user.has_perm("trainings.can_view_%s" % get_args_model(self)):
            raise PermissionDenied
        context = super(TrainingsDetail, self).get_context_data(**kwargs)
        context['argument'] = self.kwargs.get('arg')
        return context


class TrainingsCreateView(CreateView):
    template_name = 'trainings/trainings_create.html'
    model = None

    def post(self, request, *args, **kwargs):
        self.object = None
        self.model = get_args_model_class(self)
        return super(TrainingsCreateView, self).post(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        if not self.request.user.has_perm("trainings.add_%s" % get_args_model(self))\
        and not request.user.is_superuser:
            raise PermissionDenied
        self.model = get_args_model_class(self)
        return super(TrainingsCreateView, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(TrainingsCreateView, self).get_context_data(**kwargs)
        context['units'] = Unit.objects.all()
        context['argument'] = self.kwargs.get('arg')
        return context


class TrainingsUpdateView(UpdateView):
    template_name = 'trainings/trainings_create.html'

    def get_queryset(self):
        if self.kwargs.get('arg') == 'rsis':
            return TrainingsRSIS.objects.all()
        elif self.kwargs.get('arg') == 'workers':
            return TrainingsWORK.objects.all()
        else:
            raise Http404()

    def get(self, request, *args, **kwargs):
        if not self.request.user.has_perm("trainings.add_%s" % get_args_model(self))\
        and not request.user.is_superuser:
            raise PermissionDenied
        return super(TrainingsUpdateView, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(TrainingsUpdateView, self).get_context_data(**kwargs)
        context['units'] = Unit.objects.all()
        context['argument'] = self.kwargs.get('arg')
        return context


def exportexcel(request, arg, object_pk):
    if arg == 'rsis':
        train = TrainingsRSIS.objects.get(pk=object_pk)
    elif arg == 'workers':
        train = TrainingsWORK.objects.get(pk=object_pk)
    else:
        raise Http404()

    if not request.user.has_perm("trainings.can_view_%s" % train._meta.module_name):
        raise PermissionDenied

    from xlwt import Workbook

    wb = Workbook()
    ws = wb.add_sheet(u'Обучение')
    i = 0
    for item in train.employees.all():
        ws.write(i, 0, item.__unicode__())
        i = i + 1

    fname = 'Обучение.Отчёт-%s.%s.%s.xls' % (datetime.now().day, datetime.now().month, datetime.now().year)
    response = HttpResponse(mimetype="application/vnd.ms-excel")
    response['Content-Disposition'] = 'attachment; filename=%s' % fname

    wb.save(response)

    return response
